<template>
  <div class="storeInfo-box">
    <div class="content-box w-card">
      <div class="content-title">
        <h1>创建新商户</h1>
      </div>
      <div class="content-info">
        <div>
          <div class="info-content">
            <el-form ref="storeInfoRef" :model="storeInfo" :rules="storeInfoRules">
              <div class="info-title">基础信息</div>
              <el-row>
                <el-col :span="8">
                  <el-form-item prop="shopName" style="width:80%" label="商户名称">
                    <el-input v-model="storeInfo.shopName" clearable placeholder="请输入商户名称" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item prop="shopUserName" style="width:80%" label="联系人">
                    <el-input v-model="storeInfo.shopUserName" clearable placeholder="请输入联系人" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item prop="shopUserPhone" style="width:80%" label="联系电话">
                    <el-input v-model="storeInfo.shopUserPhone" clearable placeholder="请输入联系电话" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item prop="firstPassword" style="width:60%" label="登录密码">
                    <el-input v-model="storeInfo.firstPassword" type="password" show-password clearable placeholder="请输入登录密码" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item prop="payFirstPassword" style="width:60%" label="支付密码">
                    <el-input v-model="storeInfo.payFirstPassword" type="password" show-password clearable
                      placeholder="请输入支付密码" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item prop="secondPassword" style="width:60%" label="确认登录密码">
                    <el-input v-model="storeInfo.secondPassword" type="password" show-password clearable placeholder="请输入登录密码" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item prop="paySecondPassword" style="width:60%" label="确认支付密码">
                    <el-input v-model="storeInfo.paySecondPassword" type="password" show-password clearable
                      placeholder="请输入支付密码" />
                  </el-form-item>
                </el-col>
              </el-row>
              <div class="info-title">商户实名信息</div>
              <el-form-item prop="auditStatus" style="width:80%" label="商户类型">
                <el-radio-group v-model="storeInfo.auditStatus">
                  <el-radio :label="1">个人商户</el-radio>
                  <el-radio :label="2">企业商户</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-row>
                <el-col v-if="storeInfo.auditStatus == 1" :span="24">
                  <el-form-item prop="idcardUrl" label="身份证人像面照片">
                    <img v-show="!storeInfo.idcardUrl" style="width:100px;cursor:pointer" src="@a/imgs/u23.png" alt=""
                      @click="uploadImg(1)">
                    <div class="upload-box" v-show="storeInfo.idcardUrl">
                      <img :src="storeInfo.idcardUrl" alt="">
                      <el-icon color="#ffffff" class="upload-close" @click="removeImg(1)">
                        <Close />
                      </el-icon>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col v-if="storeInfo.auditStatus == 2" :span="24">
                  <el-form-item prop="licenseUrl" label="营业执照">
                    <img v-show="!storeInfo.licenseUrl" style="width:100px;cursor:pointer" src="@a/imgs/u23.png" alt=""
                      @click="uploadImg(2)">
                    <div class="upload-box" v-show="storeInfo.licenseUrl">
                      <img :src="storeInfo.licenseUrl" alt="">
                      <el-icon color="#ffffff" class="upload-close" @click="removeImg(2)">
                        <Close />
                      </el-icon>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
              <div class="info-title">其它设置</div>
              <el-form-item prop="cooperateType" style="width:80%" label="合作方式">
                <el-radio-group v-model="storeInfo.cooperateType">
                  <el-radio :label="3">混合(代理+分销)</el-radio>
                  <el-radio :label="1">代理(H5链接)</el-radio>
                  <el-radio :label="2">分销(API对接)</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-row>
                <el-col :span="8">
                  <el-form-item prop="cooperateStartTime" style="width:80%" label="合约开始时间">
                    <el-date-picker value-format="x" v-model="storeInfo.cooperateStartTime" type="date" placeholder="合约开始时间" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item prop="cooperateEndTime" style="width:80%" label="结束时间">
                    <el-date-picker value-format="x" v-model="storeInfo.cooperateEndTime" type="date" placeholder="结束时间" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item prop="auditStatus" label="销售权限">
                <el-tree ref="treeRef" :data="treeData" show-checkbox node-key="goodsId" highlight-current :props="defaultProps"
                  @check-change="treeChange" />
              </el-form-item>
              <el-form-item prop="autoType" style="width:80%" label="是否销售所有授权商品">
                <el-switch v-model="storeInfo.autoType" :active-value="1" :inactive-value="2" />
              </el-form-item>
              <el-form-item prop="operationalStatus" style="width:80%" label="商户状态">
                <el-radio-group v-model="storeInfo.operationalStatus">
                  <el-radio :label="1">启用</el-radio>
                  <el-radio :label="0">禁用</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-row>
                <el-col :span="8">
                  <el-form-item prop="tjUnique" style="width:80%" label="推荐人">
                    <el-select style="width:100%" filterable v-model="storeInfo.tjUnique" clearable placeholder="请选择推荐人">
                      <el-option v-for="item in tjOptions" :key="item.tjUnique" :label="item.tjName" :value="item.tjUnique" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </div>
        <div class="btn-box">
          <el-button @click="backHandle">取消</el-button>
          <el-button type="primary" @click="confirmHandle" :loading="loading">确定创建</el-button>
        </div>
      </div>
    </div>
  </div>
  <input ref="uploadInputRef" style="display:none" type="file" accept="image/*" @change="uploadChange">
</template>

<script>
import { onMounted, reactive, ref, toRefs, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { successDeal, warningDeal } from '@/utils/utils'
import axios from "axios"
import hexMD5 from "@/utils/md5.min.js"
import api from './api'
export default {
  setup() {
    const route = useRoute()
    const router = useRouter()

    const storeInfoRef = ref(null)
    const uploadInputRef = ref(null)
    const treeRef = ref(null)

    const validatePass = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请再次确认密码'))
      }
      if (value != state.storeInfo.firstPassword) {
        callback(new Error('两次密码不相同'))
      }
      if (value === state.storeInfo.firstPassword) {
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请再次确认密码'))
      }
      if (value != state.storeInfo.payFirstPassword) {
        callback(new Error('两次密码不相同'))
      }
      if (value === state.storeInfo.payFirstPassword) {
        callback()
      }
    }

    const imgUrlPass = (rule, value, callback) => {
      if (!state.storeInfo.idcardUrl) {
        callback(new Error('请上传身份证人像面照片'))
      } else {
        callback()
      }
    }

    const imgUrlPass2 = (rule, value, callback) => {
      if (!state.storeInfo.licenseUrl) {
        callback(new Error('请上传营业执照'))
      } else {
        callback()
      }
    }

    const state = reactive({
      loading: false,
      storeInfo: {
        auditStatus: 1,
        cooperateType: 3,
        operationalStatus: 1,
      },
      allGoods: [],
      treeData: [],
      fileForm: {},
      tjOptions: [],
      uploadIndex: null,
      defaultProps: {
        label: 'goodsName',
        children: 'children',
      },
      storeInfoRules: {
        shopName: [
          { required: true, message: '请输入商户名称', trigger: 'blur' },
        ],
        shopUserName: [
          { required: true, message: '请输入联系人', trigger: 'blur' },
        ],
        shopUserPhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/, message: '手机号码格式不正确', trigger: 'blur'
          }
        ],
        firstPassword: [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
          {
            pattern: /^[a-zA-Z0-9]{6,}$/, message: '请输入6位以上且只包含数字、字母的密码', trigger: 'blur'
          },
        ],
        payFirstPassword: [
          { required: true, message: '请输入支付密码', trigger: 'blur' },
          {
            pattern: /^[a-zA-Z0-9]{6,}$/, message: '请输入6位以上且只包含数字、字母的密码', trigger: 'blur'
          },
        ],
        secondPassword: [
          { required: true, validator: validatePass, trigger: 'blur' },
        ],
        paySecondPassword: [
          { required: true, validator: validatePass2, trigger: 'blur' },
        ],
        auditStatus: [
          { required: true, message: '请选择商户类型', trigger: 'blur' },
        ],
        idcardUrl: [
          { required: true, validator: imgUrlPass, trigger: 'blur' },
        ],
        licenseUrl: [
          { required: true, validator: imgUrlPass2, trigger: 'blur' },
        ],
        cooperateType: [
          { required: true, message: '请选择合作方式', trigger: 'blur' },
        ],
        cooperateStartTime: [
          { required: true, message: '请选择合约开始时间', trigger: 'blur' },
        ],
        cooperateEndTime: [
          { required: true, message: '请选择结束时间', trigger: 'blur' },
        ],
        operationalStatus: [
          { required: true, message: '请选择商户状态', trigger: 'blur' },
        ],
      },
    })

    function backHandle() {
      router.go(-1)
    }

    function uploadImg(i) {
      state.uploadIndex = i
      uploadInputRef.value.click()
    }

    async function uploadChange(e) {
      state.fileForm = {}
      state.fileForm.file = e.target.files[0]
      state.fileForm.fileName = e.target.files[0].name
      await uploadFile()
      uploadInputRef.value.value = ''
    }

    async function uploadFile() {
      let param = new FormData()
      param.append('file', state.fileForm.file, state.fileForm.fileName)
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data',
          token: '',
          Authorization: `'','','',3,20,''`,
          platformHeadType: 'ilinkPlatform',
        }
      }
      let url = '/ums/file/upload/img'
      if (PROCESS_ENV.ENVIRONMENT == 'Production') {
        url = '/coupon_h5' + url
      }
      await axios.post(url, param, config).then(res => {
        if (res.data.code == '200') {
          if (state.uploadIndex == 1) {
            state.storeInfo.idcardUrl = res.data.data.ossUrl
          } else if (state.uploadIndex == 2) {
            state.storeInfo.licenseUrl = res.data.data.ossUrl
          }
        } else {
          warningDeal(res.data.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function removeImg(i) {
      state.fileForm = {}
      if (i == 1) {
        state.storeInfo.idcardUrl = null
      } else if (i == 2) {
        state.storeInfo.licenseUrl = null
      }
    }

    let myArr = []
    function getChooseGoods(list) {
      list && list.map(item => {
        if (state.allGoods.includes(item)) {
          myArr.push(item)
        }
        if (list.children) {
          getChooseGoods(list.children)
        }
      })
      return myArr
    }

    function confirmHandle() {
      if (state.loading) return
      storeInfoRef.value.validate((valid, fields) => {
        if (valid) {
          state.loading = true
          myArr = []
          const obj = {
            ...state.storeInfo,
            authGoodsIds: getChooseGoods(state.storeInfo.authGoodsIds),
            firstPassword: hexMD5(state.storeInfo.firstPassword),
            payFirstPassword: hexMD5(state.storeInfo.payFirstPassword),
            secondPassword: hexMD5(state.storeInfo.secondPassword),
            paySecondPassword: hexMD5(state.storeInfo.paySecondPassword),
          }
          api.registerShop(obj).then(res => {
            if (res.code == '200') {
              successDeal(res.msg)
              backHandle()
            } else {
              warningDeal(res.msg)
            }
            state.loading = false
          }).catch(err => {
            console.log(err)
            state.loading = false
          })
        }
      })
    }

    function setTree(list) {
      list && list.map(item => {
        item.children = item.categoryTreeInfoList || item.brandTreeInfoList || item.goodsTreeInfoList
        item.goodsName = item.typeName || item.categoryName || item.brandName || item.goodsName
        item.goodsId = item.goodsId || item.brandId || item.categoryId || item.typeId
        item.parentId = item.brandId || item.categoryId || item.typeId
        if (item.children) {
          setTree(item.children)
        }
      })
    }

    function getTree() {
      api.goodsInfoTree().then(res => {
        if (res.code == '200') {
          state.treeData = res.data
          setTree(state.treeData)
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function treeChange() {
      let myArr = treeRef.value.getCheckedNodes()
      const menuIdList = []
      myArr.map(item => {
        if (item.parentId) {
          menuIdList.push(item.parentId)
        }
        menuIdList.push(item.goodsId)
      })
      state.storeInfo.authGoodsIds = menuIdList
    }

    function getGoodsId(list) {
      const myArr = []
      list && list.map(item => {
        item.goodsId && myArr.push(item.goodsId)
      })
      return myArr
    }

    function getGoods() {
      const obj = {
        page: 1,
        size: 100000,
      }
      api.goodsInfoSearch(obj).then(res => {
        if (res.code == '200') {
          state.allGoods = getGoodsId(res.data.records)
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function getTjOptions() {
      const obj = {

      }
      api.tuijianuser(obj).then(res => {
        if (res.code == '200') {
          state.tjOptions = res.data?.list
        }
      }).catch(err => {
        console.log(err)
      })
    }

    onMounted(() => {
      getTree()
      getGoods()
      getTjOptions()
    })

    return {
      ...toRefs(state),
      storeInfoRef,
      uploadInputRef,
      treeRef,
      backHandle,
      uploadImg,
      removeImg,
      uploadChange,
      confirmHandle,
      treeChange,
    }
  }
}
</script>

<style lang="scss" scoped>
.storeInfo-box {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  flex-flow: column;
  gap: 20px;
  .tips-box {
    background: url("@a/imgs/tips-background.png") no-repeat;
    background-size: 100% 100%;
    color: #ffffff;
    box-sizing: border-box;
    padding: 20px;
    border-radius: 5px;
    > div {
      display: flex;
      align-items: center;
      gap: 10px;
    }
    > span {
      display: block;
      margin-top: 10px;
      font-size: 14px;
    }
  }
  .content-box {
    box-sizing: border-box;
    padding: 20px;
    .content-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      > h1 {
        font-size: 16px;
      }
    }
    .content-info {
      width: 100%;
      .info-title {
        font-size: 14px;
        font-weight: bold;
        display: flex;
        align-items: center;
        gap: 5px;
        margin-left: -20px;
        padding-bottom: 10px;
        &::before {
          content: "";
          display: block;
          height: 16px;
          width: 4px;
          background-color: #0081ff;
        }
      }
      > div {
        width: 100%;
        box-sizing: border-box;
        padding: 20px 0;
        .info-content {
          width: 100%;
          box-sizing: border-box;
          padding: 0 20px;
          > div {
            font-size: 14px;
            display: flex;
            width: 100%;
            margin-top: 20px;
            > div {
              width: 50%;
              color: #5f5f66;
              > span {
                color: #000000;
              }
            }
          }
          .img-box {
            display: flex;
          }
        }
      }
      > div:first-of-type {
        border-bottom: 1px dashed #d4d4d4;
      }
    }
  }
}
.btn-box {
  text-align: right;
  padding-bottom: 0 !important;
}
.upload-box {
  position: relative;
  > img {
    max-width: 150px;
    max-height: 80px;
  }
  .upload-close {
    position: absolute;
    right: 0;
    top: 0;
    cursor: pointer;
    background-color: rgba($color: #000000, $alpha: 0.5);
  }
}
</style>